frappe.call({
    method: "zelin_export_excel_template.api.get_export_excel_template"
})
.then((r) => {
    if (!r.exc && r.message && r.message.length) {
        let uniqueDoctypes = [...new Set(r.message.map(item => item.reference_doctype))];
        
        uniqueDoctypes.forEach((dt) => {
            frappe.ui.form.on(dt, {
                refresh: function(frm) {
                    
                    // 确保新的工具类已加载
                    if (!frappe.zelin || !frappe.zelin.export_excel_utils) {
                        console.warn("frappe.zelin.export_excel_utils not loaded yet.");
                        return;
                    }
                    
                    let data = r.message.filter(item => { 
                        if (item.reference_doctype !== dt) { 
                            return false;
                        } 
                        
                        const currentDoc = frm ? frm.doc : null;
                        
                        // Evaluate the condition_expression (保持不变)
                        if (item.condition) {
                            try {
                                const conditionFunc = new Function('doc', `return ${item.condition}`);
                                return conditionFunc(currentDoc);
                            } catch (e) {
                                console.error(`Error evaluating condition for template ${item.template_name}:`, e);
                                return false;
                            }
                        } 
                        return true;
                    });
                    
                    if (frappe.model.can_print(frm.doctype) && !frm.is_new()) {
                        let pdfDropdown = { label: __("Export PDF"), items: [] };
                        let excelDropdown = { label: __("Export Excel"), items: [] };
                        
                        // 收集所有模板
                        data.forEach(d => {
                            const action = () => frappe.zelin.export_excel_utils.handleExport(frm.doc, d, d.enable_export_pdf ? 'pdf' : 'excel');

                            if (d.enable_export_pdf) {
                                pdfDropdown.items.push({
                                    label: __(d.template_name),
                                    action: () => frappe.zelin.export_excel_utils.handleExport(frm.doc, d, 'pdf')
                                });
                            }
                            
                            if (d.enable_export_excel) {
                                excelDropdown.items.push({
                                    label: __(d.template_name),
                                    action: () => frappe.zelin.export_excel_utils.handleExport(frm.doc, d, 'excel')
                                });
                            }
                        });
                        
                        // 添加下拉菜单到工具栏
                        if (pdfDropdown.items.length > 0) {
                            pdfDropdown.items.forEach(item => {
                                frm.add_custom_button(item.label, item.action, pdfDropdown.label);
                            });
                        }
                        
                        if (excelDropdown.items.length > 0) {
                            excelDropdown.items.forEach(item => {
                                frm.add_custom_button(item.label, item.action, excelDropdown.label);
                            });
                        }
                    }
                }
            });
        });
    }
});